<?php
/**
 * PHP 时间处理函数
 * 修改编码格式:统一编码：UTF-8
 * @author Tujt 2015-09-18
 */
class PHPCache {
    public function  __construct(){
    	#codeing
    }
    /**
     * 获取redis对象
     * @author Toby.tu 2017-04-11
     */
    public function getRedis(){
        static $phpredis_cache_object;//增加静态变量，防止同一个进程多次链接redis
        if(!$phpredis_cache_object){//初始化redis类
            include_once APPPATH.'libraries/predis/Autoloader.php';
            \Predis\Autoloader::register();
            $redis_host = config_item('redis_config');
            $redis_config = array(
                'scheme' => 'tcp',
                'host'   => $redis_host['host'],
                'port'   => $redis_host['port'],
            );
            $phpredis_cache_object = new \Predis\Client($redis_config);
        }
        return $phpredis_cache_object;
    }
    /**
     * 加密字符串
     * @author Toby.tu 2016-12-16
     */
    public function pwd($key=''){
        if(empty($key)) return '';
        $label = config_item('phpcache_redis_key');
        $label .= 'phpcache_redis_key';
        return md5(sha1($key.$label).sha1($label.$key));
    }
    /**
     * 存入缓存
     * @author Toby.tu 2017-04-13
     */
    public function set($key='',$data='$$_cache_&&_data_##',$time=60){
    	if(empty($key)) return false;//没有键值
        if('$$_cache_&&_data_##' == $data) return false;//空
        if(!empty($data)) $val = serialize($data);
        else $val = '';
        $key = $this->pwd($key);//对键值进行加密，防止重复
        $redis = $this->getRedis();//获取redis对象
        $redis->set($key,$val);
        $redis->expire($key,$time);
    }
    /**
     * 取缓存
     * @author Toby.tu 2017-04-13
     */
    public function get($key){
    	if(empty($key)) return array();
        static $phpredis_cache_getdata;//增加静态变量，同一个缓存不多次读取
        $key = $this->pwd($key);//对键值进行加密，防止重复
        if(isset($phpredis_cache_getdata[$key])){//缓存已经读取过一次
            return $phpredis_cache_getdata[$key];
        }
        $data = '';
        $redis = $this->getRedis();//获取redis对象
        $cachedata = $redis->get($key);
        if(!empty($cachedata)) $data = unserialize($cachedata);
        return $phpredis_cache_getdata[$key] = $data;
    }
    /**
     * 删除缓存
     * @author Toby.tu 2017-04-11
     */
    public function rm($key=''){
        if(!empty($key)){
            $key = $this->pwd($key);//对键值进行加密，防止重复
	    	$redis = $this->getRedis();//获取redis对象
			$redis->del($key);//删除缓存
        }
    }
}
?>
